package com.ict.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ict.api.entity.IctOrder;
import com.ict.api.entity.IctOrderItem;
import com.ict.api.result.ApiResponse;
import com.ict.api.vo.IctOrderDetailVO;
import com.ict.api.vo.IctOrderItemVO;
import com.ict.mapper.IctOrderItemMapper;
import com.ict.mapper.IctOrderMapper;
import com.ict.service.IctOrderItemService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 订单商品明细表 服务实现类
 * </p>
 *
 * @author wjp
 * @since 2025-03-23
 */
@Service
public class IctOrderItemServiceImpl extends ServiceImpl<IctOrderItemMapper, IctOrderItem> implements IctOrderItemService {

    @Resource
    private IctOrderMapper orderMapper;

    @Resource
    private IctOrderItemMapper orderItemMapper;

    @Override
    public ApiResponse<IctOrderDetailVO> getOrderDetail(Long orderId) {
        // 查询订单基本信息
        IctOrder order = orderMapper.selectById(orderId);
        if (order == null) {
            return ApiResponse.error("订单不存在");
        }

        // 查询订单商品明细
        List<IctOrderItem> orderItems = orderItemMapper.selectList(
                new LambdaQueryWrapper<IctOrderItem>().eq(IctOrderItem::getOrderId, orderId)
        );

        // 转换为 VO 视图对象
        List<IctOrderItemVO> orderItemVOList = orderItems.stream().map(item -> {
            IctOrderItemVO itemVO = new IctOrderItemVO();
            itemVO.setProductId(item.getProductId());
            itemVO.setProductName(item.getProductName());
            itemVO.setProductQuantity(item.getProductQuantity());
            itemVO.setProductPrice(item.getProductPrice());
            return itemVO;
        }).collect(Collectors.toList());

        // 封装订单详情 VO
        IctOrderDetailVO orderDetailVO = new IctOrderDetailVO();
        orderDetailVO.setOrderId(order.getId());
        orderDetailVO.setOrderSn(order.getOrderSn());
        orderDetailVO.setTotalAmount(order.getTotalAmount());
        orderDetailVO.setStatus(order.getStatus());
        orderDetailVO.setItems(orderItemVOList);

        return ApiResponse.success(orderDetailVO);
    }

}
